// pages/shortVideo/index.js
import {shortVideoAPI} from '../../api/shortvideo/index'
import {commonAPI} from '../../api/common/index'
import {shoppingAPI} from '../../api/public/index'
import {$await,timeAgo} from '../../utils/util'
import runtime from '../../utils/runtime'
import config from '../../config'
const img_url = 'https://images.weserv.nl/?url='
import face from '../../utils/emoji'
const face_online_path = "https://images.weserv.nl/?url=https://img001.cbct.cn/image/face/"
let userInfo = wx.getStorageSync('userInfo')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoType:'',// 视频填充方式
    shopinfo:{},
    // 表情包
    faceList:face.map(item => ({...item,url:`${face_online_path}${item.url}`})),
    inputBottom:0,
    _keyboardShow:false,
    emoji:false,
    page:1,
    atInfo:{},
    msgType:'',
    focus:false,
    hiddenDel:true,
    animationData:{},
    animationShop:{},// 商品弹框动画
    show:false, // 评论列表显示
    videoInfo:null,
    commentList:[], // 评论列表
    isPlay:true,
    sendContent:'',// 评论框内容
    placeholderContent:'说点什么',// 输入框提示文字


  },
  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: function (options) {
    this.getVideoInfo(options.number)
    let animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
   onReady: function () {
    // 获取到video实例
    this.videoContext = wx.createVideoContext('myvideo',this)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 视频元数据加载完触发
  bindloadedmetadata(e){
    const {detail:{width,height}} = e
    if(width < height){
      this.setData({videoType:'fill'})
    }
  },
  // 商品列表
  async getShopList(){
    const {channel_id,number} = this.data.videoInfo
    let params = {
      number,
      channel_id
    }
    let [err,res] = await $await(shoppingAPI.productLisAPI({...params}))
    if(res){
      res.list = res.list && res.list.map(item => {
        return {
          ...item,
          image:`${img_url}${item.image}`
        }
      })
      this.setData({shopinfo:res})
    }
  },
  setEmoji({detail}){
    let {sendContent} = this.data
    sendContent+=detail
    this.setData({sendContent})
  },
  showEmoji(){
    this.setData({emoji:this.data._keyboardShow || !this.data.emoji})
    wx.nextTick(()=>{
      let query = this.createSelectorQuery().in(this)
      query.select('#emoji').boundingClientRect()
      query.exec((rect)=>{
        this.setData({
          inputBottom:rect[0].height,
          focus:false
        })
      })
    })
  },
  deleteEmoji() {
    const pos = Number(this.data.sendContent.length)
    const comment = this.data.sendContent
    let result = '',
      cursor = 0

    let emojiLen = 6
    let startPos = pos - emojiLen
    if (startPos < 0) {
      startPos = 0
      emojiLen = pos
    }
    const str = comment.slice(startPos, pos)
    const matchs = str.match(/\[([\u4e00-\u9fa5\w]+)\]$/g)
    // 删除表情
    if (matchs) {
      const rawName = matchs[0]
      const left = emojiLen - rawName.length
      const emojiNames = this.data.faceList.map(item => (item.content))
      if (emojiNames.indexOf(rawName) >= 0) {
        const replace = str.replace(rawName, '')
        result = comment.slice(0, startPos) + replace + comment.slice(pos)
        cursor = startPos + left
      }
      // 删除字符
    } else {
      let endPos = pos - 1
      if (endPos < 0) endPos = 0
      const prefix = comment.slice(0, endPos)
      const suffix = comment.slice(pos)
      result = prefix + suffix
      cursor = endPos
    }
    this.setData({
      sendContent: result,
      // cursor: cursor
    })
  },
  onkeyboardHeightChange(e) {
    const {height} = e.detail
    wx.nextTick(()=>{
      this.setData({
        inputBottom: height
      })
    })
  },
  bindblur(e){
    this.data._keyboardShow = false
    wx.nextTick(()=>{
      setTimeout(() => {
        if(!this.data.emoji){
          this.setData({
            focus:false
          },()=>{
            this.setData({inputBottom:0})
          })
        }
      }, 0);
    })
  },
  bindfocus(e){
    this.data._keyboardShow = true
    this.setData({
      emoji:false,
      focus:true
      // inputBottom:e.detail.height
    })
  },
  beforeleave(){
    this.setData({
      emoji:false,
      focus:false,
      inputBottom:0
    })
  },
  nextPage(){
    this.getComment(this.data.page+1)
  },
  // 评论和评论回复的点赞和取消
  async commentStar({currentTarget:{dataset}}){
    const {info,type,cindex} = dataset
    console.log(dataset,'ssss')
    let api = info.is_star == 0 
    ? shortVideoAPI.replyCommentStar
    : shortVideoAPI.replyCommentCancelStar
    const [err,res] = await $await(api({obj_id:type == 'comment' ? info.cid : info.rid,type}))
    if(res){
      if(type == 'reply'){
        let cur = [...this.data.commentList[cindex].replyList]
        cur[dataset.rindex].is_star = info.is_star == 1 ? 0 : 1
        cur[dataset.rindex].star = info.is_star == 0 ? Number(info.star)+1 : Number(info.star)-1
        const cur_reply = `commentList[${cindex}].replyList`
        // const cur_reply_num = `commentList[${cindex}].replyList[${dataset.rindex}].star`
        this.setData({
          [cur_reply]:cur
          // [cur_reply_num]:info.is_star == 0 ? Number(info.star)+1 : Number(info.star)-1

        })
      }else if(type == 'comment'){
        const cur_comment = `commentList[${cindex}].is_star`
        const cur_comment_num = `commentList[${cindex}].star`
        this.setData({
          [cur_comment]:info.is_star == 1 ? 0 : 1,
          [cur_comment_num]:info.is_star == 0 ? Number(info.star)+1 : Number(info.star)-1
        })
      }

    }
  },
  // 关注
  async toFollow(){
    const {author,type} = this.data.videoInfo
    let followType = ''
    if(type == 1 || type == 7){
      followType = 2
    }else{
      followType = 1
    }
    let params = {
      obj_id:author,
      type:followType
    }
    const [err,res] = await $await(commonAPI.follow({...params}))
    if(res){
      let isfollow = 'videoInfo.is_follow'
      this.setData({
        [isfollow]:1
      })
    }
  },
  // 显示删除评论框
  longPress({currentTarget:{dataset}}){
    const {info,type} = dataset
    console.log(info,'info')
    // return
    if(userInfo.user_id != info.number) return
    this.delId = info.cid || info.rid
    this.type = type
    this.setData({
      hiddenDel:false
    })
    this.animation.height('256rpx').step({ duration: 300 })
    this.setData({
      animationData: this.animation.export()
    })
  },
  // 取消删除评论
  cancelDel(){
    this.animation.height('0rpx').step({ duration: 300 })
    this.setData({
      animationData: this.animation.export()
    },()=>{
      wx.nextTick(()=>{
        this.setData({hiddenDel:true})
      })
    })
  },
  // 删除评论
  async del(){
    const [err,res] = await $await(shortVideoAPI.delComment({obj_id:this.delId,type:this.type}))
    if(res){
      this.setData({hiddenDel:true})
      this.getComment()
      let commentNum = 'videoInfo.comment'
      const {comment} = this.data.videoInfo
      this.setData({[commentNum]:Number(comment)-1})
    }
  },
  // 短视频点赞和取消点赞
  async isLikeVideo({currentTarget:{dataset:{status}}}){
    let {number,like} = this.data.videoInfo
    const [err,res] = await $await(shortVideoAPI.videoStar({video_id:number,type:status}))
    if(res){
      const is_like = 'videoInfo.is_like'
      const likeNum = 'videoInfo.like'
      this.setData({
        [is_like]:status == 1 ? 0 : 1,
        [likeNum]:status == 0 ? Number(like)+1 : Number(like)-1
      })
    }
  },
  // 视频播放暂停
  changePlayStatus(e){
    const {dataset:{play}} = e.currentTarget
    if(play){
      this.videoContext.play()
    }else{
      this.videoContext.pause()
    }
    this.setData({isPlay:play})
  },
  // 标题处理
  formatTitle(res){
    const atHost = (
      res.hoster && res.hoster
      .map(item => `@${item.nickname}`)
      .join(',')
      .replace(',','')
      ) || ''
    let formatTitle = res.title.split("\n")
    formatTitle = formatTitle.map((item,index) =>{
      if(index == formatTitle.length - 1){
        item = `${item} ${atHost}`
      }
      return item
    })
    return formatTitle
  },
  // 短视频信息
  async getVideoInfo(number){
    let [err,res] = await $await(shortVideoAPI.videoInfo({number}))
    if(res){
      res = {
        ...res,
        title:this.formatTitle(res),
        avatar: `${img_url}${config.imgUrlAvatar}${res.avatar}`
      }
      this.setData({videoInfo:res})
      // this.getShopList()
    }
  },
  // 短视频评论列表
  async getComment(page = 1){
    const { number } = this.data.videoInfo
    let [err,res] = await $await(shortVideoAPI.commentList({video_id:number,page,pageSize:20}))
    if(res){
      res = res.map(item => ({
        ...item,
        avatar:`${img_url}${config.imgUrlAvatar}${item.avatar}`,
        showReply:false,
        more:Number(item.more),
        created:timeAgo(item.created)
      }))
      // 表情处理
      this.data.faceList.forEach((item)=>{
        res.forEach(m =>{
          if(m.content.indexOf(item.content)!=-1){
            m.content = m.content.replaceAll(
              item.content,
              `<img class="face_msg" src="${item.url}"/>`
              )
          }
        })
      })
      if(page == 1){
        this.setData({commentList:res})
      }else {
        let {commentList}  = this.data
        commentList = [].concat(...commentList,...res)
        this.setData({commentList,page})
      }
    }
  },
  // 短视频评论回复列表
  async getReply(cid,index){
    let [err,res] = await $await(shortVideoAPI.replyList({cid,page:1,pageSize:1000}))
    if(res){
      let {commentList} = this.data
      let replyItem = commentList[index]
      let current = `commentList[${index}]`
      res = res.map(item => ({
        ...item,
        avatar:`${img_url}${config.imgUrlAvatar}${item.avatar}`,
        created:timeAgo(item.created)
      }))
      // 表情处理
      this.data.faceList.forEach((item)=>{
        res.forEach(m =>{
          if(m.content.indexOf(item.content)!=-1){
            m.content = m.content.replaceAll(
              item.content,
              `<img class="face_msg" src="${item.url}"/>`
              )
          }
        })
      })
      replyItem['replyList'] = res
      this.setData({[current]:replyItem})
    }
  },
  // 发评论
  async send({detail:{value}}){
    if(!userInfo || !userInfo.token){
      return wx.navigateTo({
        url:'/pages/login/login'
      })
    }
    if(this.data.msgType){
      this.sendATComment(value)
    }else{
      this.sendComment(value)
    }

  },
  // 评论
  async sendComment(value){
    const {number} = this.data.videoInfo
    let [err,res] = await $await(shortVideoAPI.videoComment({video_id:number,content:value}))
    if(res){
      this.getComment()
      let commentNum = 'videoInfo.comment'
      const {comment} = this.data.videoInfo
      this.setData({
        [commentNum]:Number(comment)+1,
        sendContent:'',
        msgType:'',
        placeholderContent:`说点什么`,
      })
    }
  },
  // 回复
  async sendATComment(value){
    const {number} = this.data.videoInfo
    const atInfo = this.data.atInfo
    let cid = atInfo.type == 'comment'?atInfo.info.cid:atInfo.pinfo.cid
    let params = {
      video_id:number,
      content:value,
      cid
    }
    if(atInfo.type == 'reply'){
      params = {...params,parent_id:atInfo.info.rid}
    }
    let [err,res] = await $await(shortVideoAPI.replyComment({...params}))
    if(res){
      // this.getReply(cid,atInfo.index)
      this.getComment()
      let commentNum = 'videoInfo.comment'
      const {comment} = this.data.videoInfo
      this.setData({
        [commentNum]:Number(comment)+1,
        sendContent:'',
        msgType:'',
        placeholderContent:`说点什么`,
      })
    }
  },
  // 回复信息
  atComment({currentTarget:{dataset}}){
    const {info,type,msgtype} = dataset
    if(userInfo.user_id == info.number) return
    console.log(dataset)
    this.setData({
      placeholderContent:`回复:${dataset.info.name}`,
      focus:true,
      msgType:dataset.msgtype,
      atInfo:dataset
    })
    
    
    
  },
  // 显示隐藏评论回复
  openReply(e){
    const {dataset} = e.currentTarget
    const {index,commentinfo:{cid},status} = dataset
    if(status) this.getReply(cid,index)
    let showReply = `commentList[${index}].showReply`
    this.setData({[showReply]:status})
  },
  // 显示评论
  showComment(){
    this.getComment()
    this.setData({
      show:true,
      msgType:'',
      placeholderContent:`说点什么`,
      page:1
    })
  },
  // 隐藏评论
  exit(){
    this.setData({show:false})
  },
  // 显示商品列表
  showShop(e){
    const {show} = e.currentTarget.dataset
    if(show){
      this.getShopList()
    }
    this.setData({shop:true})
    this.animation.height('788rpx').step({ duration: 300 })
    this.setData({
      animationShop: this.animation.export()
    })
  },
  hideShop(){
    this.animation.height('0rpx').step({ duration: 300 })
    this.setData({
      animationShop: this.animation.export()
    },()=>{
      wx.nextTick(()=>{
        this.setData({shop:false})
      })
    })
  },
  // 商品详情
  buy({currentTarget:{dataset:{info}}}){
    const {id} = info
    let ds_token = wx.getStorageSync('userInfo').ds_token
    let oId = wx.getStorageSync('userInfo').openid
    let url = `${config.dsUrl}/detail/${id}?from1=wxapp&isToken=${ds_token}&oId=${oId}`
    wx.navigateTo({
      url: '/pages/webview/webview?webURL=' + encodeURIComponent(url),
    })
  },
  // 商品橱窗
  displayWindow(){
    let channel_id = this.data.videoInfo.channel_id
    let ds_token = wx.getStorageSync('userInfo').ds_token
    let oId = wx.getStorageSync('userInfo').openid
    let url = `${config.dsUrl}/goods_list/${channel_id}?from1=wxapp&isToken=${ds_token}&oId=${oId}`
    wx.navigateTo({
      url: '/pages/webview/webview?webURL=' + encodeURIComponent(url),
    })
  }
})